<?php
/**
 * Created by PhpStorm.
 * User: LG
 * Date: 2017/8/31
 * Time: 14:46
 */

namespace app\common\model;


use think\Db;
use think\Model;
/*
 *  总后台
 *  区域合伙人板块
 */
class Operation extends Model
{
    protected $db;
    protected $db_user;
    protected $profile;
    protected $profile_user;
    protected $engineers;
    protected $db_name_log = 'admin_log';
    protected $areas_db = 'areas';
    public function __construct()
    {
        parent::__construct();
        //区域合伙人
        $this->db = Db::name("operation_info");
        $this->db_user = Db::name("operation_user");
        //行政区域
        $this->profile = Db::name("administrative_info");
        $this->profile_user = Db::name("administrative_user");
        //工程人员
        $this->engineers = Db::name("engineers");
        //地址
        $this->areas_db = Db::name('areas');
    }

    /*
	 *  统计区域合伙人数量
	 *  @author ligang
	 *  @param  $where      条件
	 *  @param  $whereTime  时间条件['字段'=>'规则']
	 *  @return int
	 */
    public function CountOperationNumber($where,$whereTime,$join=[])
    {
        if (empty($join)){
            if (empty($whereTime)){
                $result = $this->db->where($where)->count();
            }else{
                if (!is_array($whereTime)){
                    return "时间必须是数组,以键值对形式";
                }
                $whereTimeKey = array_keys($whereTime);
                $result = $this->db->where($where)->whereTime($whereTimeKey[0],$whereTime[$whereTimeKey[0]])->count();
            }
        }else{
            if (empty($whereTime)){
                $result = $this->db->where($where)->join($join)->count();
            }else{
                if (!is_array($whereTime)){
                    return "时间必须是数组,以键值对形式";
                }
                $whereTimeKey = array_keys($whereTime);
                $result = $this->db->join($join)->where($where)->whereTime($whereTimeKey[0],$whereTime[$whereTimeKey[0]])->count();
            }
        }
        return $result;
    }

    /**
     *  新增一条运行中心数据
     * @author  李港
     * @param   array   $data  新增数据
     * @return  int     成功则返回当前ID
     */
    public function insertOperation($data)
    {
        $result = $this->db->insert($data);
        $OperationId = $this->db->getLastInsID();
        if ($result == 1){
            writelog($this->user_data['uid'],$this->user_data['username'],'用户【'.$this->user_data['username'].'】新增成功：区域合伙人→'.$data['company_name'],1,$this->db_name_log);
            return $OperationId;
        }else{
            writelog($this->user_data['uid'],$this->user_data['username'],'用户【'.$this->user_data['username'].'】新增失败：区域合伙人→'.$data['company_name'],0,$this->db_name_log);

        }
        return $result;
    }

    /**
     *  更新一条区域合伙人数据
     * @author  李港
     * @param   array   $data  更新数据(包含主键)
     * @return  int
     */
    public function updateOperation($data)
    {
        $result = $this->db->update($data);
        if ($result == 1){
            writelog($this->user_data['uid'],$this->user_data['username'],'用户【'.$this->user_data['username'].'】更新成功：区域合伙人→'.$data['company_name'],1,$this->db_name_log);
        }else{
            writelog($this->user_data['uid'],$this->user_data['username'],'用户【'.$this->user_data['username'].'】更新失败：区域合伙人→'.$data['company_name'],0,$this->db_name_log);

        }
        return $result;
    }

    /**
     *  更新一条区域合伙人【账号】数据
     * @author  李港
     * @param   array   $data  更新数据(包含主键)
     * @param   array   $where 更新条件
     * @return  int
     */
    public function updateOperationAccount($where,$data)
    {
        $result = $this->db_user->where($where)->update($data);
        if ($result == 1){
            writelog($this->user_data['uid'],$this->user_data['username'],'用户【'.$this->user_data['username'].'】更新成功：区域合伙人账号→'.$data['account'],1,$this->db_name_log);
        }else{
            writelog($this->user_data['uid'],$this->user_data['username'],'用户【'.$this->user_data['username'].'】更新失败：区域合伙人账号→'.$data['account'],0,$this->db_name_log);
        }
        return $result;
    }
    /**
     *  更新一条行政中心【账号】数据
     * @author  蒙明然
     * @param   array   $data  更新数据(包含主键)
     * @param   array   $where 更新条件
     * @return  int
     */
    public function updateAdministrativenAccount($where,$data)
    {
       
        $result = $this->profile_user->where($where)->update($data);
        if ($result == 1){
            writelog($this->user_data['uid'],$this->user_data['username'],'用户【'.$this->user_data['username'].'】更新成功：行政中心账号→'.$data['account'],1,$this->db_name_log);
        }else{
            writelog($this->user_data['uid'],$this->user_data['username'],'用户【'.$this->user_data['username'].'】更新失败：行政中心账号→'.$data['account'],0,$this->db_name_log);
        }
        return $result;
    }

    /**
     *  更新一条行政中心数据
     * @author  李港
     * @param   array   $data  更新数据(包含主键)
     * @return  int
     */
    public function updateAdministrativen($data)
    {
        $result = $this->profile->update($data);
        if ($result == 1){
            writelog($this->user_data['uid'],$this->user_data['username'],'用户【'.$this->user_data['username'].'】更新成功：行政区域',1,$this->db_name_log);
        }else{
            writelog($this->user_data['uid'],$this->user_data['username'],'用户【'.$this->user_data['username'].'】更新失败：行政区域：',0,$this->db_name_log);

        }
        return $result;
    }

    /**
     *  新增一条行政中心数据
     * @author  李港
     * @param   array   $data  新增数据
     * @return  int
     */
    public function insertAdministrativen($data)
    {
        $result = $this->profile->insertGetId($data);
        if ($result == 1){
            writelog($this->user_data['uid'],$this->user_data['username'],'用户【'.$this->user_data['username'].'】新增成功：行政区域',1,$this->db_name_log);
        }else{
            writelog($this->user_data['uid'],$this->user_data['username'],'用户【'.$this->user_data['username'].'】新增失败：行政区域',0,$this->db_name_log);

        }
        return $result;
    }

    /**
     *  查询一条区域合伙人中心数据
     * @author  李港
     * @param   array   $where  条件（一维数组）
     * @return  array
     */
    public function findOperation($where)
    {
        return $this->db->where($where)->find();
    }

    /**
     *  查询一条行政中心数据
     * @author  李港
     * @param   array   $where  条件（一维数组）
     * @return  array
     */
    public function findAdministrative($where)
    {
        return $this->profile->where($where)->find();
    }
    /**
     *  查询绑定区域数据
     * @author  蒙明然
     * @return  array
     */
    // public function findArea($id)
    // {
    //     $val=[];
    //     if(is_array($id)){
    //         foreach ($id as $v){
    //             $val = $this->profile->where(['area_id' =>  ['like','%'.$v.'%'],'is_delete'=>0])->find();
    //         }
    //         return $val;
    //     }else{
    //         return $this->profile->where(['area_id' =>  ['like','%'.$id.'%']])->find();
    //     }
    // }
      /**
     *  查询绑定区域数据
     * @author  蒙明然
     * @return  array
     */
    public function findArea($id)
    {
        $val=[];
        if(is_array($id)){
            foreach ($id as $v){
                $sql =  $sql = "select * from rq_administrative_info where locate(',".$v.",',area_id)";
                $val = Db::query($sql);
            }
            return $val;
        }else{
            $sql =  $sql = "select * from rq_administrative_info where locate(',".$id.",',area_id)";
            return Db::query($sql);
        }
    }

    /*
     * 查询一条工程人员数据
     * @author  李港
     * @param   array   $where    条件（一维数组）AND
     * @param   array   $whereOR  条件（一维数组）OR
     * @return  array
     */
    public function findEngineers($where = array(),$whereOR = array())
    {
        return $this->engineers->where($where)->whereOr($whereOR)->find();
    }

    /*
     *  新增一条工程人员数据
     *  @author  李港
     *  @param   array   $data  新增数据
     *  @return int
     */
    public function insertEngineers($data)
    {
        $result = $this->engineers->insert($data);
        if ($result == 1){
            writelog($this->user_data['uid'],$this->user_data['username'],'用户【'.$this->user_data['username'].'】新增成功：工程人员',1,$this->db_name_log);
        }else{
            writelog($this->user_data['uid'],$this->user_data['username'],'用户【'.$this->user_data['username'].'】新增失败：工程人员',0,$this->db_name_log);

        }
        return $result;
    }

    /**
     *  更新一条工程人员数据
     * @author  李港
     * @param   array   $data  更新数据(包含主键)
     * @return  int
     */
    public function updateEngineers($data)
    {
        $result = $this->engineers->update($data);
        if ($result == 1){
            writelog($this->user_data['uid'],$this->user_data['username'],'用户【'.$this->user_data['username'].'】更新成功：工程人员',1,$this->db_name_log);
        }else{
            writelog($this->user_data['uid'],$this->user_data['username'],'用户【'.$this->user_data['username'].'】更新失败：工程人员：',0,$this->db_name_log);

        }
        return $result;
    }

    /**
     *  区域合伙人ID计算行政区域数量
     * @author  李港
     * @param   array   $where  条件（一维数组）
     * @return  int
     */
    public function getAdministrative($where = [])
    {
        $result = $this->profile->where(['is_delete'=>0])->where($where)->count();
        return $result;
    }

    /**
     *  区域合伙人分页查询
     * @author  李港
     * @param   int     $page   当前页
     * @param   array   $where  条件（一维数组）
     * @return  array
     */
    public function selectPage($page = 1,$where=array()){
        //时间
        if(!empty($where['datetimeStart'])&&!empty($where['datetimeEnd'])){
            $datetimeStart = intval(strtotime($where['datetimeStart']));
            unset($where['datetimeStart']);
            $datetimeEnd = intval(strtotime($where['datetimeEnd']))+24*3600;
            unset($where['datetimeEnd']);
            $where['add_time']=array('between',[$datetimeStart,$datetimeEnd]);
        }
        //-----------------------------
        $Configuration = new Configuration();
        $limits = intval($Configuration->getkey('pagesize'));
        //限制查询（只查询没有被逻辑删除的数据）
        $where['rq_operation_info.is_delete'] = 0;
        $count = $this->db->where($where)->count();//计算总页面
        $allpage = intval(ceil($count / $limits));
        $lists = $this->db->where($where)->field('
        rq_operation_info.company_name,
        rq_operation_info.`name`,
        rq_operation_info.phone,
        rq_operation_info.province_name,
        rq_operation_info.add_time,
        rq_operation_info.o_id,
        rq_operation_info.note
        ')->page($page, $limits)->order('add_time','desc')->select();
        $data = array();
        $data['data'] = $lists;
        $data['page'] = [
            'count'=>$count,
            'allpage'=>$allpage,
        ];
        return $data;
    }


    /**  李港
     *   删除（逻辑删除）
     * @param $table  表名
     * @param $field  条件字段
     * @param $id     条件
     * @param $type   被操作的模块
     * @return int
     */
    public function deleteData($table, $field, $id, $type)
    {
        $result = Db::name($table)->where(array("{$field}"=>$id))->setField('is_delete',1);
//        $res =db('operation_user')->where(array("{$field}"=>$id))->setField('is_delete',1);
        if ($result !== 1) {
            writelog($this->user_data['uid'],$this->user_data['username'],'用户【'.$this->user_data['username'].'】删除失败：'.$type.'：'.$id,0,$this->db_name_log);
            return false;
        }
        writelog($this->user_data['uid'],$this->user_data['username'],'用户【'.$this->user_data['username'].'】删除成功：'.$type.'：'.$id,1,$this->db_name_log);
        return $result;
    }

    /**
     *  行政区域分页查询
     * @author  李港
     * @param   int     $page   当前页
     * @param   array   $where  条件（一维数组）
     * @return  array
     */
    public function selectDataProfile($page = 1,$where = array())
    {
        //时间
        $datetimeStart = '1970-10-1';
        $datetimeEnd = time();
        if (!empty($where['datetimeStart'])){
            $datetimeStart = intval(strtotime($where['datetimeStart']));
        }
        if (!empty($where['datetimeEnd'])){
            $datetimeEnd = intval(strtotime($where['datetimeEnd']))+24*3600;
        }
        unset($where['datetimeStart']);
        unset($where['datetimeEnd']);
        //-----------------------------
        $Configuration = new Configuration();
        $limits = intval($Configuration->getkey('pagesize'));
        $join = [
            ['rq_operation_info','rq_administrative_info.operation = rq_operation_info.o_id']
        ];
        //限制查询（只查询没有被逻辑删除的数据）
        $where['rq_administrative_info.is_delete'] = 0;
        $count = $this->profile->alias('i')->where($where)->whereTime('rq_administrative_info.add_time','between',[$datetimeStart,$datetimeEnd])->join($join)->count();//计算总页面
        $allpage = intval(ceil($count / $limits));
        $lists = $this->profile->alias('i')->where($where)->whereTime('rq_administrative_info.add_time','between',[$datetimeStart,$datetimeEnd])->join($join)->field('
        i.company_name as administrative_company_name,
        i.area_id,
        rq_operation_info.company_name as operation_company_name,
        i.a_id,
        i.area_name,
        i.add_time,
        i.phone,
        i.note,
        i.status,
        i.`name`')->page($page, $limits)->select();
        $data = array();
        $data['data'] = $lists;
        $data['page'] = [
            'count'=>$count,
            'allpage'=>$allpage,
        ];
        return $data;
    }

    /*
     * 工程人员分页查询
     * @author  李港
     * @param   int     $page   当前页
     * @param   array   $where  条件（一维数组）
     * @return  array
     */
    public function selectPageEngineers($page = 1,$where = array())
    {
        /*
         *  SQL原生
         */
        //获取分页设置
        $Configuration = new Configuration();
        $limits = intval($Configuration->getkey('pagesize'));
        $where['rq_engineers.is_delete'] = 0;
        $join = [
            ['rq_administrative_info','rq_engineers.administrative_id = rq_administrative_info.a_id'],
            ['rq_operation_info','rq_administrative_info.operation = rq_operation_info.o_id']
        ];
        $count = $this->engineers->where($where)->join($join)->count();//计算总页面
        $allpage = intval(ceil($count / $limits));
        //组装搜索条件
        $whereString = "";
        foreach ($where as $key=>$value){
            if (is_array($where[$key])){
                $whereString .= $key." ".implode(" ",$where[$key])." AND ";
                continue;
            }
            $whereString .= $key."=".$value." AND ";
        }
        $whereString = substr($whereString,0,-5);
        if ($whereString){
            $whereString = " WHERE ".$whereString;
        }
        //设置分页
        $page = intval($limits*($page-1));
        $lists = Db::query("
                SELECT
                rq_engineers.engineers_id,
                rq_engineers.engineers_name,
                rq_engineers.reg_time,
                rq_engineers.engineers_idcard,
                rq_engineers.engineers_address,
                rq_engineers.note,
                rq_engineers.avatar_img,
                rq_engineers.engineers_number,
                rq_engineers.engineers_phone,
                rq_engineers.engineers_status,
                rq_administrative_info.a_id,
                rq_administrative_info.company_name as administrative_company_name,
                rq_operation_info.o_id,
                rq_operation_info.company_name as operation_company_name,
                COUNT(if(work_order_status>4,true,null )) as complete_number
                FROM
                rq_engineers
                INNER JOIN rq_administrative_info ON rq_engineers.administrative_id = rq_administrative_info.a_id
                INNER JOIN rq_operation_info ON rq_administrative_info.operation = rq_operation_info.o_id
                LEFT JOIN rq_work_order ON rq_engineers.engineers_id = rq_work_order.repair_id
                {$whereString}
                GROUP BY
                rq_engineers.engineers_id
                LIMIT {$page},{$limits}
        ");
        $data = array();
        $data['data'] = $lists;
        $data['page'] = [
            'count'=>$count,
            'allpage'=>$allpage,
        ];
        return $data;
    }

    /**
     * 获取所有区域合伙人地址数据
     * @author ligang
     * @param array $where  条件
     * @return array|bool
     */
    public function selectOperationInfo($where=[])
    {
        $where['is_delete'] = 0;
        $res = Db::name('operation_info')->field('o_id,company_name,province_name,province_id')->where($where)->select();
        return $res;
    }

    /**
     * 获取所有行政中心数据
     * @author ligang
     * @param   array    $where    查询条件（一维数组）
     * @return array|bool
     */
    public function selectAdministrativeInfo($where=array())
    {
        $res = Db::name('administrative_info')->where($where)->where(array('is_delete'=>0))->field('a_id,company_name,area_name,area_id')->select();
        return $res;
        exit();
        //对多行政区域的处理
        $data = array();
        foreach ($res as $key => $value){
            if(strpos($value['area_name'],',') != false){
                $a_id = $value['a_id'];
                $company_name = $value['company_name'];
                $arr_area_name = explode(',',$value['area_name']);
                $arr_area_id = explode(',',$value['area_id']);
                foreach ($arr_area_name as $k=>$v){
                    $data[$k]['a_id'] = $a_id;
                    $data[$k]['company_name'] = $company_name;
                    $data[$k]['area_name'] = $v;
                    $data[$k]['area_id'] = $arr_area_id[$k];
                }
            }else{
                array_push($data,$value);
            }
        }
        //去除相同的区域
        $i = 0;
        foreach ($data as $kk => $vv){
            if ($i+1<count($data)){
                if (in_array($vv['a_id'],$data[$i+1])){
                    $i = 0;
                    array_splice($data, $kk, 1);
                }else{
                    $i++;
                }
            }
            continue;
        }
        return $data;
    }

    /**
     * 绑定账号
     * @author  ligang
     * @param   int     $type   模块（1区域合伙人绑定，2行政中心绑定,3区域合伙人检查，4行政区域检查,5更新行政区域账号）
     * @param   array   $data   数据
     * @param   array   $where  条件
     * @return bool|array|int
     */
    public function bindAccount($type,$where=[],$data = [])
    {
        switch ($type){
            case 1:
                $addAccount = $this->db_user->insertGetId($data);
                Db::name('operation_auth_group_access')->insert(['uid'=>$addAccount,'group_id'=>1]);
                if ($addAccount){
                    writelog($this->user_data['uid'],$this->user_data['username'],'用户【'.$this->user_data['username'].'】新增成功：区域合伙人账号→'.$data['account'],1,$this->db_name_log);
                    return $addAccount;
                }else{
                    writelog($this->user_data['uid'],$this->user_data['username'],'用户【'.$this->user_data['username'].'】新增失败：区域合伙人账号→'.$data['account'],0,$this->db_name_log);
                    return false;
                }
                break;
            case 2:
                $addAccount = $this->profile_user->insert($data);
                if ($addAccount){
                    return $addAccount;
                }else{
                    return false;
                }
                break;
            case 3:
                $findOperationAccount = $this->db_user->where($where)->find();
                if ($findOperationAccount){
                    return $findOperationAccount;
                }
                return false;
                break;
            case 4:
                $findOperationAccount = $this->profile_user->where($where)->find();
                if ($findOperationAccount){
                    return $findOperationAccount;
                }
                return false;
                break;
            case 5:
                $findOperationAccount = $this->profile_user->where($where)->update($data);
                if ($data['status'] == 0){
                    $data['engineers_status'] = 1;
                }else{
                    $data['engineers_status'] = 2;
                }
                $where['administrative_id'] = $where['a_id'];
                unset($data['status']);
                unset($where['a_id']);
                $update = $this->engineers->where($where)->update($data);
                if ($findOperationAccount || $update){
                    return $findOperationAccount;
                }
                return false;
                break;
            default:
                return  "非法请求";
        }
    }
    /**
     * 获取所有行政中心用户组
     * @author ligang
     * @return array|bool
     */
    public function getAdministrativeGroup()
    {
        return Db::name('administrative_auth_group')->select();
    }

    /*
     *  地址(省)
     * @param   array    $where    查询条件（一维数组）
     */
    public function areasProvince($where=array())
    {
        $where['parent_id'] = 0;
        //省
        $province = $this->areas_db->where($where)->select();
        return $province;
    }

    /*
     *  地址(市)
     */
    public function areasCity($province_id = '')
    {
        //省
        if (!empty($province_id)){
            $where['parent_id'] = $province_id;
        }else{
            $where = '1=1';
        }
        $province = $this->areas_db->where($where)->select();
        return $province;
    }

    /*
     *  地址(区/县)
     */
    public function areaName($city_id = '')
    {
        if (!empty($city_id)){
            $where['parent_id'] = $city_id;
        }else{
            $where = '1=1';
        }
        $areaName = $this->areas_db->where($where)->select();
        return $areaName;
    }

    /**
     * 查找area名字
     * @author 蒙明然
     * @param $id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function findAddrName($id, $field = '*'){
        if (!empty($id)) {
            if(is_array($id)){
                foreach ($id as $k => $value) {
                    $where['id'] = $id[$k];
                    $name[] = $this->areas_db->where($where)->field($field)->find();
                }
            }else{
                $where['id']=$id;
                $temp = $this->areas_db->where($where)->field($field)->select();
                $name=$temp[0]['area_name'];
            }
        }else{$name=null;}
        return $name;
    }

    /**
     *    获取区域合伙人数据
     * @param array $where
     * @return int|string
     */
    public function getCount($where=[])
    {
        $result = $this->db->where($where)->count();
        return $result;
    }
    //获取区域合伙人列表
    public function getAll($where=[],$field='*'){
        return $this->db->where($where)->field($field)->select();
    }

    /**
     * 查询一条区域合伙人信息
     */
    public function findOne($where, $field = '*')
    {

        $result = $this->db->where($where)->field($field)->find();
        // 判断结果 并返回
        if ($result == false) {
            return false;
        }
        return $result;
    }



}